package indi.jp.project.core.controller;

import indi.jp.project.core.config.PropertyConfig;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sys/file")
public class FileController {

    @Autowired
    private PropertyConfig propertyConfig;

    @PostMapping("/upload")
    @ResponseBody
    public JsonResult upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        if (file.isEmpty()) {
            return JsonResult.failure("请选择文件");
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String storageName = RandomUtil.getRandomString(16) + suffix;
        String path = propertyConfig.getAttachment().getPath();

        try {
            File folder = new File(path);
            if (!folder.exists()) {
                folder.mkdir();
            }
            File dest = new File(path + storageName);
            file.transferTo(dest);
            Map<String, Object> map = new HashMap<>();
            map.put("fileName", fileName);
            map.put("fileSuffix", suffix);
            map.put("storageName", storageName);
            map.put("storagePath", path + storageName);
            return JsonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }
}
